//
//  RHLocalPackVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/4/8.
//

#import "RHLocalPackVC.h"
#import "RHLocalPackItemCell.h"
#import "RHLocalDevPackModel.h"
#import "RHBatteryCellFullChartVC.h"
#import "RHLocalPackDetailVC.h"

#import "RHLocalSettingModel.h"
#import "RHBleCmdManager.h"
#import "RHBleCmdData.h"
#import "CBLEDataParse.h"
#import "JCDataConvert.h"

@interface RHLocalPackVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UICollectionView *collectView;

@property (nonatomic, strong) NSArray *packDataArr;//数据源

@property (nonatomic, strong) NSMutableArray *packArray;//默认读取8个pack,能读取值的显示
//读取pack信息的index
@property (nonatomic, assign) NSInteger packCmdIndex;

@property (nonatomic, strong) RHLocalDevPackModel *lastModel;

@property (nonatomic, assign) NSInteger packCount;

@property (nonatomic, assign) BOOL hasReadPackCount;

@end

@implementation RHLocalPackVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"PACK";
    [ProgressHUDManage shareObject].showErrorTips = NO;//这个页面不弹错误提示
    [self setupUI];
    self.packCount = 8;
    NSMutableArray *mtbArr = [NSMutableArray array];
    for (int i = 0; i < self.packCount; i++) {
        RHLocalDevPackModel *packModel = [[RHLocalDevPackModel alloc]init];
        packModel.title = [NSString stringWithFormat:@"PACK %d#",i+1];
        packModel.packIndex = i;
        [mtbArr addObject:packModel];
    }
    self.packArray = mtbArr;
    [self readPackInfo];
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [ProgressHUDManage shareObject].showErrorTips = NO;//这个页面不弹错误提示
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [ProgressHUDManage shareObject].showErrorTips = YES;
}
#pragma mark ------ 获取pack数量,改为通过循环读取pack sn
//-(void)getDevicePackCount
//{
//    self.hasReadPackCount = NO;
//    self.packCmdIndex = 0;
//    NSDictionary *snDic = @{
//        @"field":@"Pck_PACKSN",
//        @"regAddr":@(4200),
//        @"bitWidth":@(256),
//        @"cmdType":@(101)
//    };
//    NSMutableArray *mtbArr = [NSMutableArray array];
//    for (int i = 0; i<self.packCount; i++) {
//        RHLocalSettingModel *settingModel = [RHLocalSettingModel yy_modelWithJSON:snDic];
//        settingModel.cmdType = [NSString stringWithFormat:@"%d",101+i];
//        [mtbArr addObject:settingModel];
//    }
//
//    self.cmdArray = mtbArr.copy;
//
//    [[RHBleCmdManager shareMnger] readDeviceInfoFromBle:self.cmdArray];
//}

-(void)receiveDeviceMsg:(NSNotification *)no
{
    [super receiveDeviceMsg:no];
    if(!self.recieveMsg)return;
    NSDictionary *dic = [no object];
    if(dic.allKeys.count==0)return;
    NSLog(@"------>收到设备信息:%@",dic);
    //读取失败
    if ([dic[CMD_CODE] integerValue]>=128) {
        NSLog(@"----->当前pack index:%ld",self.packCmdIndex);
        [[RHBleCmdManager shareMnger] cancelTimeOutAction];
        if(self.packCmdIndex<self.packCount-1){
            self.packCmdIndex++;//读下一个pack
            [self readPackInfo];
        }
        return;
    }
    [self.cmdArray enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
        
        if(obj.regAddr == [dic[CMD_ADDRESS] integerValue] ){
            
            NSData *data = dic[CMD_ADDRESS_VALUE];
            NSString *parse_content = [CBLEDataParse parseData:data settingModel:obj];
            NSLog(@"---->%@ = %@",obj.field,parse_content);
            
            if([obj.field isEqualToString:@"Pck_PACKSN"]){
                parse_content = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            }
            if([obj.field isEqualToString:@"Pck_SwVerH"] && data.length == 2){
                NSData *softWare_H = [data subdataWithRange:NSMakeRange(0, 1)];
                NSInteger h_value = [JCDataConvert dataToInt:softWare_H];
                NSData *softWare_L = [data subdataWithRange:NSMakeRange(1, 1)];
                NSInteger l_value = [JCDataConvert dataToInt:softWare_L];
                parse_content = [NSString stringWithFormat:@"%ld.%03ld",h_value,l_value];
            }
            
            [self.dataDic setObject:parse_content forKey:obj.field];
            //读取到pack数量
//            if([obj.field isEqualToString:@"Mtr_PackCnt"]){
//                self.hasReadPackCount = YES;
//                self.packCount = [parse_content integerValue]>0? [parse_content integerValue]:1;
//                NSMutableArray *mtbArr = [NSMutableArray array];
//                for (int i = 0; i < self.packCount; i++) {
//                    RHLocalDevPackModel *packModel = [[RHLocalDevPackModel alloc]init];
//                    packModel.title = [NSString stringWithFormat:@"PACK %d#",i+1];
//                    [mtbArr addObject:packModel];
//                }
//                self.packDataArr = mtbArr.copy;
//            }
            
            //读取完一个pack的信息
            if([obj.field isEqualToString:@"Pck_RSOC"]){
                if(self.packCmdIndex<self.packCount){
                    RHLocalDevPackModel *packModel = self.packArray[self.packCmdIndex];
                    [self updatePackInfoWithModel:packModel data:self.dataDic];
                }
                self.packCmdIndex++;
                
            }
        }
    }];
    
//    [self.collectView reloadData];
}

-(void)sendCmdFinish
{
    if (!self.recieveMsg) {
        return;
    }
    NSLog(@"----->读完一个pack信息  packCmdIndex:%ld",self.packCmdIndex);
//    if(self.hasReadPackCount){
        //8个pack已读完,能读到值的显示
        if(self.packCmdIndex >= self.packCount-1){
            [self.collectView endHeaderRefresh];
            return;
        }
        NSMutableArray *arr = [NSMutableArray array];
        [self.packArray enumerateObjectsUsingBlock:^(RHLocalDevPackModel*  _Nonnull packModel, NSUInteger idx, BOOL * _Nonnull stop) {
            if (packModel.sn.length > 0) {
                [arr addObject:packModel];
            }
        }];
        self.packDataArr = arr.copy;//
        [self.collectView reloadData];
        [self.collectView endHeaderRefresh];
        [self readPackInfo];
//    }
}

#pragma mark ------ 读取pack下的数据
-(void)readPackInfo
{
    NSArray *cmdArr = @[@{
        @"field":@"Pck_PACKSN",
        @"regAddr":@(4200),
        @"bitWidth":@(256),
        @"cmdType":@(101 + self.packCmdIndex)
    },@{
        @"field":@"Pck_HT",
        @"regAddr":@(7),
        @"bitWidth":@(16),
        @"ratio":@"0.1",
        @"dataType":@"signed",
        @"cmdType":@(101 + self.packCmdIndex)
    },@{
        @"field":@"Pck_SwVerH",
        @"regAddr":@(3002),
        @"bitWidth":@(16),
        @"cmdType":@(101 + self.packCmdIndex)
    },@{
        @"field":@"Pck_CycleIndex",
        @"regAddr":@(4012),
        @"bitWidth":@(16),
        @"cmdType":@(101 + self.packCmdIndex)
    },@{
        @"field":@"Pck_RSOC",
        @"regAddr":@(17),
        @"bitWidth":@(32),
        @"ratio":@"0.001",
        @"cmdType":@(101 + self.packCmdIndex)
    }];
    
    NSMutableArray *mtbArr = [NSMutableArray array];
    [cmdArr enumerateObjectsUsingBlock:^(NSDictionary  *_Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        RHLocalSettingModel *settingModel = [RHLocalSettingModel yy_modelWithJSON:dic];
        [mtbArr addObject:settingModel];
    }];
    self.cmdArray = mtbArr.copy;
    
    [[RHBleCmdManager shareMnger] readDeviceInfoFromBle:self.cmdArray];
    
}


-(void)updatePackInfoWithModel:(RHLocalDevPackModel*)packModel data:(NSMutableDictionary*)dic
{
    NSLog(@"------>更新pack信息:%@",dic);
    if(dic[@"Pck_PACKSN"]){
        packModel.sn = dic[@"Pck_PACKSN"];
    }
    
    if(dic[@"Pck_SwVerH"]){
        packModel.softWare = dic[@"Pck_SwVerH"];
    }
    
    if(dic[@"Pck_CycleIndex"]){
        packModel.cycleCount = dic[@"Pck_CycleIndex"];
    }
    
    if(dic[@"Pck_RSOC"]){
        packModel.remainCap = dic[@"Pck_RSOC"];
    }
    
    if(dic[@"Pck_HT"]){
        packModel.maxTemp = dic[@"Pck_HT"];
    }
}

-(void)setupUI
{
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_ACK,receiveDeviceMsg:);
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_FINISH,sendCmdFinish);
    
    UIView *topView = kView;
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_offset(0);
        make.height.mas_offset(30);
    }];
    UIView *normalPoint = kView;
    normalPoint.backgroundColor = kRGB(57, 222, 63);
    normalPoint.layer.cornerRadius = 5;
    [topView addSubview:normalPoint];
    [normalPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(10, 10)));
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    QMUILabel *norLab = [QMUILabel labelWithText:@"正常".rh_localized font:kSYSTEMFONT(12) textColor:kColorRGBA(63, 68, 67, 0.6)];
    [topView addSubview:norLab];
    [norLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(normalPoint.mas_right).offset(15);
        make.centerY.equalTo(normalPoint);
    }];
    
    UIView *faultPoint = kView;
    faultPoint.backgroundColor = kRGB(255, 108, 97);
    faultPoint.layer.cornerRadius = 5;
    [topView addSubview:faultPoint];
    [faultPoint mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.equalTo(@(CGSizeMake(10, 10)));
        make.left.equalTo(norLab.mas_right).offset(25);
        make.centerY.mas_offset(0);
    }];
    
    QMUILabel *faultLab = [QMUILabel labelWithText:@"异常".rh_localized font:kSYSTEMFONT(12) textColor:kColorRGBA(63, 68, 67, 0.6)];
    [topView addSubview:faultLab];
    [faultLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(faultPoint.mas_right).offset(15);
        make.centerY.equalTo(normalPoint);
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    _collectView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectView.backgroundColor = CFTabViewBgColor;
    _collectView.showsVerticalScrollIndicator = NO;
    _collectView.showsHorizontalScrollIndicator = NO;
    _collectView.delegate = self;
    _collectView.dataSource = self;
    [_collectView registerClass:[RHLocalPackItemCell class] forCellWithReuseIdentifier:@"RHLocalPackItemCell"];
    [self.view addSubview:_collectView];
    
    
    [_collectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(topView.mas_bottom);
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(0);
    }];
    kWeakSelf;
    [_collectView addHeaderRefresh:^{
        weakSelf.packCmdIndex = 0;
        [weakSelf readPackInfo];
    }];
}



- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.packDataArr.count;
    
    
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    RHLocalPackItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"RHLocalPackItemCell" forIndexPath:indexPath];
    RHLocalDevPackModel *packModel = self.packDataArr[indexPath.item];
    cell.packModel = packModel;
    return cell;
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    CGFloat w = (kUI_WINDOW_W -30-10)/2;
    CGFloat h = w * 0.82;
    return CGSizeMake(w, h);
    
    
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    return UIEdgeInsetsMake(15, 15, 15, 15);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    
    return 10;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 10;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    RHLocalPackDetailVC *cellVC = [[RHLocalPackDetailVC alloc]init];
    RHLocalDevPackModel *packModel = self.packDataArr[indexPath.item];
    cellVC.packSN = packModel.sn;
    cellVC.packIndex = packModel.packIndex;
    [self.navigationController pushViewController:cellVC animated:YES];
}

@end
